const XLSX = require("xlsx");
const fs = require("fs");

function writeToExcel({ dir }) {
  //校验目录是否存在
  if (!fs.existsSync(dir)) {
    return {
      msg: "目录不存在",
      data: [],
    };
  }

  const files = fs.readdirSync(dir);

  let fileData = [];
  files.forEach((v) => {
    fileData.push({
      fileName: v.replace(/\.json$/, ""),
      data: JSON.parse(fs.readFileSync(dir + "/" + v, "utf8")),
    });
  });

  // 用第一个语种的key，作为第一列的数据
  const keys = Object.keys(fileData[0].data);

  // 添加表头
  const data = [];
  data.push(["Key", ...fileData.map((v) => v.fileName)]); // 表头作为二维数组的第一行

  // // 按行添加数据
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    data.push([key, ...fileData.map((v) => v.data[key])]);
  }
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, "Translations");
  XLSX.writeFile(wb, "translations.xlsx");
  return {
    msg: "写入成功",
    data: data,
  };
}

module.exports = writeToExcel;
